package 多线程练习;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;

public class greedy_snake extends JFrame {

    private static final int WIDTH = 600;
    private static final int HEIGHT = 600;
    private static final int CELL_SIZE = 20;
    private static final int DELAY = 150;

    private ArrayList<Point> snake;
    private Point food;
    private int direction; // 0: up, 1: right, 2: down, 3: left
    private boolean isRunning = false;
    private int score = 0;

    private GamePanel gamePanel;
    private Timer timer;

    public greedy_snake() {
        setTitle("贪吃蛇");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        gamePanel = new GamePanel();
        add(gamePanel);

        addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int key = e.getKeyCode();
                if (key == KeyEvent.VK_UP && direction != 2) direction = 0;
                else if (key == KeyEvent.VK_RIGHT && direction != 3) direction = 1;
                else if (key == KeyEvent.VK_DOWN && direction != 0) direction = 2;
                else if (key == KeyEvent.VK_LEFT && direction != 1) direction = 3;
                else if (key == KeyEvent.VK_SPACE && !isRunning) startGame();
            }
        });

        startGame();
    }

    private void startGame() {
        snake = new ArrayList<>();
        snake.add(new Point(5, 5));
        direction = 1;
        score = 0;
        spawnFood();
        isRunning = true;

        if (timer != null) timer.stop();
        timer = new Timer(DELAY, e -> {
            moveSnake();
            checkCollision();
            gamePanel.repaint();
        });
        timer.start();
    }

    private void moveSnake() {
        Point head = snake.get(0);
        Point newHead = new Point(head);

        switch (direction) {
            case 0: newHead.y--; break;
            case 1: newHead.x++; break;
            case 2: newHead.y++; break;
            case 3: newHead.x--; break;
        }

        snake.add(0, newHead);
        if (!checkFoodCollision()) {
            snake.remove(snake.size() - 1);
        }
    }

    private boolean checkFoodCollision() {
        if (snake.get(0).equals(food)) {
            score += 10;
            spawnFood();
            return true;
        }
        return false;
    }

    private void checkCollision() {
        Point head = snake.get(0);

        // 边界检测
        if (head.x < 0 || head.x >= WIDTH/CELL_SIZE ||
                head.y < 0 || head.y >= HEIGHT/CELL_SIZE) {
            gameOver();
            return;
        }

        // 自碰撞检测
        for (int i = 1; i < snake.size(); i++) {
            if (head.equals(snake.get(i))) {
                gameOver();
                return;
            }
        }
    }

    private void spawnFood() {
        Random rand = new Random();
        do {
            food = new Point(
                    rand.nextInt(WIDTH / CELL_SIZE),
                    rand.nextInt(HEIGHT / CELL_SIZE)
            );
        } while (snake.contains(food));
    }

    private void gameOver() {
        isRunning = false;
        timer.stop();
        JOptionPane.showMessageDialog(this, "游戏结束！得分: " + score);
    }

    private class GamePanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // 绘制游戏区域
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, WIDTH, HEIGHT);

            // 绘制蛇
            g.setColor(Color.GREEN);
            for (Point p : snake) {
                g.fillRect(p.x * CELL_SIZE, p.y * CELL_SIZE, CELL_SIZE - 1, CELL_SIZE - 1);
            }

            // 绘制食物
            g.setColor(Color.RED);
            g.fillOval(food.x * CELL_SIZE, food.y * CELL_SIZE, CELL_SIZE - 1, CELL_SIZE - 1);

            // 绘制分数
            g.setColor(Color.WHITE);
            g.setFont(new Font("Arial", Font.BOLD, 20));
            g.drawString("得分: " + score, 10, 20);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new greedy_snake().setVisible(true);
        });
    }
}

